<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/12/9
 * Time: 1:23 PM
 */
namespace app\lib;


use think\facade\Cache;

class Token
{
// 生成令牌

    public static function generateToken()
    {
        $randChar = getRandChars(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = md5($randChar.$timestamp);
        return md5($randChar . $timestamp . $tokenSalt);
    }

    /**
     * 添加token
     * @param $value
     * @param  $key 来源
     * @return string
     */
    public static function cacheToken($value,$key){
        $token = self::generateToken();
        $value['key'] = $key;
        //缓存30分钟
        Cache::set($token,$value,3600);
        return $token;
    }

    /**
     * 刷新token
     * @param $token
     * @return mixed
     */
    public static function refreshToken($token){
        $value = Cache::get($token);
        //缓存30分钟
        Cache::set($token,$value,3600);
        return $token;
    }

    /**
     * 验证token
     * $key 验证来源
     */
    public static function validToken($token,$key){
        if(empty($token)){
            return false;
        }
        $result = Cache::get($token);
        if(empty($result) || !isset($result['key'])){
            return false;
        }
        if($result['key'] != $key){
            return false;
        }
        self::refreshToken($token);
        return true;
    }

    /**
     * 通过token获取数据
     * @param string $key
     * @return string
     */
    public static function getDataForToken($key=''){
        $request = request();
        $token = $request->header("token");
        $result = Cache::get($token);
        if(empty($key)){
            return $result;
        }else{
            return $result[$key];
        }
    }

}